package com.rd.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.mapper.SysRoleMapper;
import com.rd.mapper.SysUserMapper;
import com.rd.pojo.SysMenu;
import com.rd.pojo.SysRole;
import com.rd.service.SysMenuService;
import com.rd.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 20586
 * @description 针对表【sys_menu】的数据库操作Service实现
 * @createDate 2023-10-16 09:01:45
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    @Override
    public List<SysMenu> buildTreeMenu(List<SysMenu> menuList) {
        //1.创建List空容器(装顶层菜单的容器)
        List<SysMenu> top = new ArrayList<>();
        //2.遍历每一个权限,查询它的子菜单查询出来,并设置
        for (SysMenu parent : menuList) {
            for (SysMenu son : menuList) {
                if (son.getParentId().equals(parent.getId())) {
                    parent.getChildren().add(son);
                }
            }
            if (parent.getParentId() == 0) {
                //说明是顶层菜单
                top.add(parent);
            }
        }
        return top;
    }

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> selectMenuByUserId(Long userId) {
        //根据用户Id获取角色
        List<SysRole> roleList = sysRoleMapper.selectRoleByUserId(userId);
        Set<SysMenu> set = new HashSet<>();
        for (SysRole sysRole : roleList) {
            Long roleId = sysRole.getId();
            //根据角色查询权限
            List<SysMenu> menuList = sysMenuMapper.selectMenuByRoleId(roleId);
            for (SysMenu sysMenu : menuList) {
                set.add(sysMenu);
            }
        }
        List<SysMenu> list = new ArrayList<>(set);
        //按照orderNum进行排序
        list.sort(Comparator.comparing(SysMenu::getOrderNum));
        return list;
    }
}




